package com.gydz.gydzbaseframeworkboot.SgsE.controller;

import com.gydz.gydzbaseframeworkboot.Common.utils.export.ExcelUtil;
import com.gydz.gydzbaseframeworkboot.Common.utils.page.PageParam;
import com.gydz.gydzbaseframeworkboot.Common.utils.page.PageUtils;
import com.gydz.gydzbaseframeworkboot.Common.utils.page.TableDataInfo;
import com.gydz.gydzbaseframeworkboot.Common.utils.result.ResultUtils;
import com.gydz.gydzbaseframeworkboot.Common.utils.sqlUtil.domain.TableSelect;
import com.gydz.gydzbaseframeworkboot.Common.utils.sqlUtil.service.SqlUtilsService;
import com.gydz.gydzbaseframeworkboot.CommonConfig.domain.BasisData;
import com.gydz.gydzbaseframeworkboot.CommonConfig.service.BasisDataService;
import com.gydz.gydzbaseframeworkboot.SgsE.domain.BilledIsup;
import com.gydz.gydzbaseframeworkboot.SgsE.domain.EInterfaceIsup;
import com.gydz.gydzbaseframeworkboot.SgsE.domain.SqlStatements;
import com.gydz.gydzbaseframeworkboot.SgsE.service.EInterfaceIsupBilledService;
import com.gydz.gydzbaseframeworkboot.SgsE.service.EInterfaceIsupService;
import com.gydz.gydzbaseframeworkboot.SgsE.service.JingTaiService;
import com.gydz.gydzbaseframeworkboot.SgsE.service.YingSheService;
import com.gydz.gydzbaseframeworkboot.SystemControl.utils.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/EInterfaceIsupBilled")
public class EinterfaceIsupBilledQueryController {
    private static final Logger log = LoggerFactory.getLogger(EInterfaceIsupQueryController.class);

    @Autowired
    YingSheService yingSheService;

    @Autowired
    private EInterfaceIsupBilledService eInterfaceIsupBilledService;


    @Autowired
    private SqlUtilsService sqlUtilsService;

    @Autowired
    private JingTaiService jingTaiService;

    @Autowired
    private BasisDataService basisDataService;

    @ResponseBody
    @Log(remark = "查询E接口呼叫记录")
    @PostMapping("/list")
    public void list(HttpServletResponse httpServletResponse, @ModelAttribute("BilledIsup") BilledIsup billedIsup) throws IOException {
        TableSelect tableSelect = new TableSelect();
        tableSelect.setTableSchema("ss7");
        tableSelect.setPrefix("grc_isup_");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        System.out.println("startime==="+billedIsup.getDtsTime());
        if(billedIsup.getDtsTime() == null){
            ResultUtils result =  ResultUtils.fail("查询E接口呼叫记录失败,请选择查询时间范围");
            ResultUtils.responseResult(httpServletResponse,result);
            return ;
        }else {
            tableSelect.setDateMin(dateFormat.format(billedIsup.getDtsTime()));
        }
        if(billedIsup.getDteTime()== null){
            billedIsup.setDteTime(new Date());
        }
        tableSelect.setDateMax(dateFormat.format(billedIsup.getDteTime()));
        List<String> tableList = sqlUtilsService.selectTabeName(tableSelect);
        if(tableList.isEmpty()){
            ResultUtils result =  ResultUtils.fail("没有该时间范围的表");
            ResultUtils.responseResult(httpServletResponse,result);
            return ;
        }


        PageUtils.startPage(new PageParam(billedIsup.getiDisplayStart(),billedIsup.getiDisplayLength(),billedIsup.getsSortDir(),billedIsup.getsSortCol()));
        billedIsup.setTableNameList(tableList);
        List<BilledIsup> list = eInterfaceIsupBilledService.SelectBilledIsup(billedIsup);
        //翻译回填字段
        if(list.size()!=0) {
            translationDataToProcess(list);
        }
        TableDataInfo tableDataInfo = PageUtils.getDataTable(list);
        ResultUtils result =  ResultUtils.succ(200,"查询E接口呼叫记录成功",tableDataInfo);
        ResultUtils.responseResult(httpServletResponse,result);
    }

    @ResponseBody
    @Log(remark = "导出E接口呼叫记录")
    @RequestMapping("/exportData")
    public void exportData(HttpServletRequest request, @ModelAttribute("BilledIsup") BilledIsup billedIsup, HttpServletResponse response) throws IOException {
        String[] excelHeader = { "起呼开始时间","起呼结束时间","主叫号码","被叫号码","OPC","DPC","CIC","采集板号","ISUP释放原因","连接号码"};
        String[] ds_titles = {"dtSTime","dtETime","uintInterfaceID","vcCallingNumber","vcCalledNumber","intOpc","intDpc","intCIC","intCardPort","intCause","vcConnectedNumber"};
        int[] widths = {256*25,256*25,  256*19, 256*19, 256*19, 256*19, 256*19, 256*19, 256*19, 256*19}; // 确保宽度数组与列数匹配
        int[] ds_format = {2,2, 2, 2,  2, 2, 2, 2, 2, 2}; // 确保格式数组与列数匹配

        TableSelect tableSelect = new TableSelect();
        tableSelect.setTableSchema("ss7"); // 修改为 ss7 表
        tableSelect.setPrefix("grc_isup_"); // 修改为 sgs_isup_ 前缀
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

        // 使用 EInterfaceIsup 的时间范围属性
        if (billedIsup.getDtsTime() == null) {
            ResultUtils result = ResultUtils.fail("查询E接口isup信令失败,请选择查询时间范围");
            ResultUtils.responseResult(response, result);
            return;
        } else {
            tableSelect.setDateMin(dateFormat.format(billedIsup.getDtsTime()));
        }

        if (billedIsup.getDteTime() == null) {
            billedIsup.setDteTime(new Date());
        }
        tableSelect.setDateMax(dateFormat.format(billedIsup.getDteTime()));

        List<String> tableList = sqlUtilsService.selectTabeName(tableSelect);
        if (tableList.isEmpty()) {
            ResultUtils result = ResultUtils.fail("没有该时间范围的表");
            ResultUtils.responseResult(response, result);
            return;
        }

        billedIsup.setTableNameList(tableList);
        List<BilledIsup> list = eInterfaceIsupBilledService.SelectBilledIsup(billedIsup); // 使用 EInterfaceIsup 服务
        // 翻译回填字段
        if (list == null || list.isEmpty()) {
            // 处理空列表的情况
            System.out.println("The list is empty or null.");
            return;
        }
        try {
            translationDataToProcess(list);
        } catch (Exception e) {
            // 捕获所有其他异常并处理
            System.err.println("An unexpected error occurred: " + e.getMessage());
            // 记录日志
            log.error("Unexpected error", e);
        }

        try {
            List<Map<String, Object>> data = new ArrayList<>();
            if (list != null && !list.isEmpty()) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                int index = 1;
                for (BilledIsup rdata : list) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("index", index);
                    map.put("dtSTime", format.format(rdata.getDtsTime()));
                    map.put("dtETime", format.format(rdata.getDteTime()));
                    map.put("uintInterfaceID", rdata.getUintInterfaceID());
                    map.put("vcCallingNumber", rdata.getVcCallingNumber());
                    map.put("vcCalledNumber", rdata.getVcCalledNumber());
                    map.put("intOpc", rdata.getIntOpc());
                    map.put("intDpc", rdata.getIntDpc());
                    map.put("intCIC", rdata.getIntCIC());
                    map.put("vcConnectedNumber", rdata.getVcConnectedNumber());
                    map.put("intCardPort", rdata.getIntCardPort());
                    map.put("intCause", rdata.getIntCause());
                    index++;
                    data.add(map);
                }
            }
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-ddHHmmss");
            ExcelUtil.export("E接口呼叫记录数据" + format.format(new Date()), "数据列表", excelHeader, ds_titles, ds_format, widths, data, request, response);
        } catch (Exception e) {
            log.error("导出数据异常", e);
        }
    }

    @PostMapping("/importData")
    public void importData(@RequestParam("file") MultipartFile file, BilledIsup billedIsup,
                           HttpServletResponse response) throws IOException {
        try {
            List<BilledIsup> importList = ExcelImportUtil.readExcel(file, BilledIsup.class, 0);
             for (BilledIsup billedIsup1 : importList) {
                 // 示例输出关键字段值
                 System.out.println("触发时间: " + billedIsup1.getDtsTime());
                 log.debug("触发时间: {}, 主叫号码: {}, 被叫号码: {}, ISUP释放原因: {}",
                         billedIsup1.getDtsTime(),
                         billedIsup1.getVcCallingNumber(),
                         billedIsup1.getVcCalledNumber(),
                         billedIsup1.getIntCause());
             }
            // 处理业务逻辑：数据校验、入库等
//            eInterfaceIsupBilledService.batchInsert(importList);
            ResultUtils.responseResult(response, ResultUtils.succ("导入成功"));
        } catch (Exception e) {
            log.error("导入异常", e);
            ResultUtils.responseResult(response, ResultUtils.fail("导入失败：" + e.getMessage()));
        }
    }


    public List<BilledIsup> translationDataToProcess(List<BilledIsup> billedIsup){

        //dpc opc静态数据
        List<BasisData> dpcOpcList = basisDataService.selectBasisDataAllIsYingShe(SqlStatements.STATIC_TABLENAME_DPC_OPC.getSql());

        //ISUP话单的BICCISUP 业务结果  List
        List<BasisData> biccIsupDList = basisDataService.selectBasisDataAll(SqlStatements.STATIC_TABLENAME_BICC_ISUP.getSql());

        //翻译ISUP业务类型             List
        List<BasisData> transmrList = basisDataService.selectBasisDataAll(SqlStatements.STATIC_TABLENAME_TRANS_MR.getSql());

        //翻译接口类型                 List
        List<BasisData> uintInterfaceIDList = basisDataService.selectBasisDataAll(SqlStatements.STATIC_TABLENAME_INTERFACE_ID.getSql());

        //翻译isup释放原因
        List<BasisData> isupReleaseTheReasonList = basisDataService.selectBasisDataAll(SqlStatements.STATIC_TABLENAME_ISUP_RELEASE_THE_REASON.getSql());
        String beiJiaoStr;
        String zhuJiaoStr;

        for (BilledIsup b : billedIsup) {
            //翻译dpc和opc
            for(BasisData bdm : dpcOpcList){
                if(bdm.getActualvalue().equals(b.getIntOpc())){
                    b.setIntOpc(bdm.getShowvalue());
                }

                if(bdm.getActualvalue().equals(b.getIntDpc())){
                    b.setIntDpc(bdm.getShowvalue());
                }
            }

            //翻译isup释放原因
            for(BasisData bdm : isupReleaseTheReasonList){
                if(bdm.getActualvalue().equals(b.getIntCause())){
                    b.setIntCause(bdm.getShowvalue());
                    break;
                }
            }

            //翻译接口类型
            for(BasisData bdm : uintInterfaceIDList){
                if(bdm.getActualvalue().equals(b.getUintInterfaceID())){
                    b.setUintInterfaceID(bdm.getShowvalue());
                    break;
                }
            }
        }


        return billedIsup;
    }

}
